<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\admin\controller;

/**
 * 商品分类管理控制器
 */
class Category extends AdminBase
{
    /**
     * 分类列表
     */
    public function categoryList()
    {
        // 使用OneBase标准getWhere模式
        $where = $this->logicCategory->getWhere($this->param);
        
        // 获取分类列表（使用OneBase标准分页）
        $result = $this->logicCategory->getCategoryList($where);
        $list = $result[0] == RESULT_SUCCESS ? $result[2] : ['data' => [], 'total' => 0];
        
        // 获取当前分类信息（用于面包屑）
        $parentId = $this->param['parent_id'] ?? 0;
        $currentCategory = null;
        if ($parentId > 0) {
            $categoryResult = $this->logicCategory->getCategoryInfo(['category_id' => $parentId]);
            $currentCategory = $categoryResult[0] == RESULT_SUCCESS ? $categoryResult[2] : null;
        }
        
        $this->assign('list', $list);
        $this->assign('parent_id', $parentId);
        $this->assign('current_category', $currentCategory);
        $this->assign('search', $this->param);
        
        return $this->fetch('category_list');
    }
    
    /**
     * 分类添加
     */
    public function categoryAdd()
    {
        if (IS_POST) {
            $result = $this->logicCategory->categoryEdit($this->param);
            $this->jump($result);
        }
        
        // 获取父分类选择器数据
        $categoryOptions = $this->logicCategory->getCategorySelector();
        if (empty($categoryOptions)) {
            $categoryOptions = [];
        }
        
        // 为添加操作设置空的info数组，确保模板中的默认值正确显示
        $this->assign('info', []);
        $this->assign('categoryOptions', $categoryOptions);
        
        return $this->fetch('category_edit');
    }
    
    /**
     * 分类编辑
     */
    public function categoryEdit()
    {
        if (IS_POST) {
            $this->param['category_id'] = $this->param['id'] ?? 0;
            $result = $this->logicCategory->categoryEdit($this->param);
            $this->jump($result);
        }
        
        $categoryId = $this->param['id'] ?? 0;
        if (!$categoryId) {
            $this->jump([RESULT_ERROR, '分类ID不能为空']);
        }
        
        // 获取分类信息
        $result = $this->logicCategory->getCategoryInfo(['id' => $categoryId]);
        if ($result[0] != RESULT_SUCCESS) {
            $this->jump([RESULT_ERROR, $result[1]]);
        }
        
        $info = $result[2];
        
        // 获取父分类选择器数据（排除自己及其子分类）
        $categoryOptions = $this->logicCategory->getCategorySelector(['exclude_id' => $categoryId]);
        if (empty($categoryOptions)) {
            $categoryOptions = [];
        }
        
        $this->assign('info', $info);
        $this->assign('categoryOptions', $categoryOptions);
        
        return $this->fetch('category_edit');
    }
    
    /**
     * 分类删除
     */
    public function categoryDelete()
    {
        $categoryId = $this->param['id'] ?? 0;
        $force = $this->param['force'] ?? false;
        
        $result = $this->logicCategory->categoryDel([
            'id' => $categoryId,
            'force' => $force
        ]);
        
        $this->jump($result);
    }
    
    /**
     * 分类详情
     */
    public function categoryDetail()
    {
        $categoryId = $this->param['id'] ?? 0;
        if (!$categoryId) {
            $this->jump([RESULT_ERROR, '分类ID不能为空']);
        }
        
        // 获取分类信息
        $result = $this->logicCategory->getCategoryInfo(['id' => $categoryId]);
        if ($result[0] != RESULT_SUCCESS) {
            $this->jump([RESULT_ERROR, $result[1]]);
        }
        
        $info = $result[2];
        
        $this->assign('info', $info);
        
        return $this->fetch('category_detail');
    }
    
    /**
     * 分类状态切换
     */
    public function categoryStatus()
    {
        $categoryId = $this->param['id'] ?? 0;
        $status = $this->param['status'] ?? 1;
        
        if (!$categoryId) {
            $this->jump([RESULT_ERROR, '分类ID不能为空']);
        }
        
        $result = $this->logicCategory->editCategory([
            'id' => $categoryId,
            'status' => $status
        ]);
        
        $this->jump($result);
    }
    
    /**
     * 批量操作
     */
    public function batch()
    {
        $ids = $this->param['ids'] ?? [];
        $action = $this->param['action'] ?? '';
        
        if (is_string($ids)) {
            $ids = explode(',', $ids);
        }
        
        $result = $this->logicCategory->batchCategory([
            'ids' => $ids,
            'action' => $action
        ]);
        
        $this->jump($result);
    }
    
    /**
     * 批量删除
     */
    public function batchDelete()
    {
        $ids = $this->param['ids'] ?? [];
        
        if (is_string($ids)) {
            $ids = explode(',', $ids);
        }
        
        $result = $this->logicCategory->batchCategory([
            'ids' => $ids,
            'action' => 'delete'
        ]);
        
        return json($result);
    }
    
    /**
     * 获取分类列表数据（AJAX）
     */
    public function getList()
    {
        $parentId = $this->param['parent_id'] ?? 0;
        
        $where = ['parent_id' => $parentId];
        
        if (!empty($this->param['status'])) {
            $where['status'] = $this->param['status'];
        }
        
        $result = $this->logicCategory->getCategoryList($where);
        
        return json($result);
    }
    
    /**
     * 获取分类选择器数据（AJAX）
     */
    public function getSelector()
    {
        $selectedId = $this->param['selected_id'] ?? 0;
        $excludeId = $this->param['exclude_id'] ?? 0;
        
        $result = $this->logicCategory->getCategorySelector([
            'selected_id' => $selectedId,
            'exclude_id' => $excludeId
        ]);
        
        return json($result);
    }
    
    /**
     * 更新排序
     */
    public function updateSort()
    {
        $sorts = $this->param['sorts'] ?? [];
        
        $result = $this->logicCategory->updateCategorySort(['sorts' => $sorts]);
        
        return json($result);
    }
    
    /**
     * 数据状态设置
     */
    public function setStatus()
    {
        $this->jump($this->logicAdminBase->setStatus('Category', $this->param));
    }
    
    /**
     * 排序
     */
    public function setSort()
    {
        $this->jump($this->logicAdminBase->setSort('Category', $this->param));
    }
    
    /**
     * 导出分类数据
     */
    public function categoryExport()
    {
        $params = [
            'parent_id' => $this->param['parent_id'] ?? '',
            'status' => $this->param['status'] ?? '',
            'keyword' => $this->param['keyword'] ?? ''
        ];
        
        $result = $this->logicCategory->getCategoryList($params);
        
        if ($result[0] != RESULT_SUCCESS) {
            $this->jump([RESULT_ERROR, $result[1]]);
        }
        
        $list = $result[2]['data'];
        
        // 导出Excel
        $header = ['ID', '分类名称', '父分类', '层级', '排序', '状态', '创建时间'];
        $data = [];
        
        foreach ($list as $item) {
            $data[] = [
                $item['id'],
                $item['name'],
                $item['parent_name'] ?? '顶级分类',
                $item['level'],
                $item['sort'],
                $item['status_text'],
                $item['create_time']
            ];
        }
        
        $filename = '商品分类数据_' . date('YmdHis') . '.xlsx';
        
        // 这里可以使用PhpSpreadsheet等库来生成Excel文件
        // 暂时返回JSON格式
        return json([
            'code' => 1,
            'msg' => '导出成功',
            'data' => [
                'header' => $header,
                'data' => $data,
                'filename' => $filename
            ]
        ]);
    }
}